package com.coin900.coin.service;

import com.coin900.coin.base.FuConstants;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by laborc on 15/12/24.
 */
public class QiniuService implements IQiniuService {
    /**
     * 获取共有资管上传凭证
     * @return
     */
    @Override
    public String getUpToken() {
        Auth auth = Auth.create(FuConstants.ACCESS_KEY, FuConstants.SECRET_KEY);
        return auth.uploadToken(FuConstants.BUCKET_NAME);
    }

    public String getUpToken(String bucketname,String key,boolean insertOnly){
        //<bucket>:<key>，表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”，已存在同名资源则会被本次覆盖。
        //如果希望只能上传指定key的文件，并且不允许修改，那么可以将下面的 insertOnly 属性值设为 1。
        //第三个参数是token的过期时间 秒为单位
        Auth auth = Auth.create(FuConstants.ACCESS_KEY, FuConstants.SECRET_KEY);
        return auth.uploadToken(bucketname, key, 3600*24, new StringMap().put("insertOnly", insertOnly?1:0));
    }

    /**
     * 获取私有资源上传凭证
     * @return
     */
    @Override
    public String getPUpToken() {
        Auth auth = Auth.create(FuConstants.P_ACCESS_KEY, FuConstants.P_SECRET_KEY);
        return auth.uploadToken(FuConstants.P_BUCKET_NAME);
    }


    public FileInfo getFileInfo(String key) throws QiniuException {
        FileInfo info=null;
        if(StringUtils.isBlank(key))return info;
        boolean b = key.startsWith("private_");
        String accessKey;
        String bucketName;
        String secretKey;
        if(b){
            accessKey=FuConstants.P_ACCESS_KEY;
            secretKey=FuConstants.P_SECRET_KEY;
            bucketName=FuConstants.P_BUCKET_NAME;
        }else{
            accessKey=FuConstants.ACCESS_KEY;
            secretKey=FuConstants.SECRET_KEY;
            bucketName=FuConstants.BUCKET_NAME;
        }
        Auth auth = Auth.create(accessKey, secretKey);
        //实例化一个BucketManager对象
        BucketManager bucketManager = new BucketManager(auth);
        //要测试的空间和key，并且这个key在你空间中存在
            //调用stat()方法获取文件的信息
            info = bucketManager.stat(bucketName, key);

        return info;
    }

   @Override
   public void upload(byte[] data,String key) throws IOException{
        UploadManager uploadManager = new UploadManager();
        try {
                //调用put方法上传
                Response res = uploadManager.put(data, key, getUpToken(FuConstants.BUCKET_NAME,key,false));
                //打印返回的信息
                System.out.println(res.bodyString());
            } catch (QiniuException e) {
                Response r = e.response;
                // 请求失败时打印的异常的信息
                System.out.println(r.toString());
                try {
                    //响应的文本信息
                    System.out.println(r.bodyString());
                } catch (QiniuException e1) {
                    //ignore
                }
            }
        }

    /**
     * 获取私有资源下载凭证
     * @param baseUrl
     * @return
     */
    @Override
    public String getDownloadToken(String baseUrl) {
        Auth auth = Auth.create(FuConstants.P_ACCESS_KEY, FuConstants.P_SECRET_KEY);
        String s = auth.privateDownloadUrl(baseUrl, 3600);
        return s;
    }

    public  String getDownloadURL(String url){
        if(StringUtils.isBlank(url))return null;
        boolean b = url.startsWith("private_");
        if(b){
            url=this.getDownloadToken(FuConstants.P_BUCKET_DOMAIN+"/"+url);
        }
        return url;
    }

    @Override
    public String getFullUrl(String url) {
        if(StringUtils.isBlank(url))return null;
        boolean b = url.startsWith("http");
        if(!b){
            b = url.startsWith("private_");
            if(b){
                url=this.getDownloadToken(FuConstants.P_BUCKET_DOMAIN+"/"+url);
            }else{
                url=FuConstants.BUCKET_DOMAIN+"/"+url;
            }
        }
        return url;
    }

    public String convertPURL(String htmlTxt){
        Pattern p_src = Pattern.compile("src=\"([^\"]+)\"");
        Matcher m_src = p_src.matcher(htmlTxt);
        Map<String,String> map =new HashMap<>();
        while (m_src.find()) {
            String src = m_src.group();
            if(src.indexOf("private_")!=-1){
                Pattern p_url = Pattern.compile(FuConstants.P_BUCKET_DOMAIN+"/private_([^\"]+)\"");
                Matcher m_url = p_url.matcher(src);
                while (m_url.find()) {
                    String url = m_url.group();
                    url=url.replaceAll("\"","");
                    String downloadToken = this.getDownloadToken(url);
                    map.put(url,downloadToken);
                }

            }
        }
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()){
            String key = iterator.next();
            String downloadToken = map.get(key);
            htmlTxt= htmlTxt.replaceAll(key,downloadToken);
        }
        return htmlTxt;
    }
}
